<?php

class Task{

	/**
	 * 添加
	 *
	 * @param unknown_type $name
	 * @param unknown_type $parent
	 * @param unknown_type $ord
	 */
	function add($data){
		
		$data['created'] = full_date();
		
		$m = M('Task');
		//返回自增id
		$id = $m->add($data);
		
		return $id;
	}
	
	/**
	 * 修改
	 *
	 * @param unknown_type $id
	 * @param unknown_type $upItems
	 * @return unknown
	 */
	function update($id,$upItems){
		$m = M('Task');
		return $m -> where('task_id='.$id)->save($upItems);
	}
	
	function get_by_task_id($id){
		
		$m = M('Task');
		return $m->table('task t')
		->join('admin a ON a.id = t.business_admin_id')
		->join('users u ON u.user_id = t.user_id')
		->join('plantform p ON p.plantform_id = u.plantform_id')
		->join("status_type stp ON stp.status_id = t.pay_status AND stp.type_code= 'task_pay_status'")
		->join("status_type sts ON sts.status_id = t.task_status AND sts.type_code= 'task_status'")
		->field("
				t.*,
				a.real_name,
				p.plantform_name,
				u.plantform_id,
				u.user_name,
				u.shop_name,
				u.shop_url,
				u.mobile_phone,				
				REPLACE(stp.status_style,'#string',stp.status_name) AS pay_status_name,
				REPLACE(sts.status_style,'#string',sts.status_name) AS task_status_name,
				DATE_FORMAT(t.begin_time,'%Y-%m-%d') AS begin_time_fmt,
				DATE_FORMAT(t.end_time,'%Y-%m-%d') AS end_time_fmt")
		->where('t.task_id='.$id)
		->find();
		
	}

	/**
	 * 
	 * 批量添加订单
	 * @param $task
	 * @param $orders
	 */
	function add_orders($orders){

		$add_count = 0;
		
		foreach ($orders as $order){
			//商品
			$goods = array(
                'goods_id'      => item_id($order['goods_url']),
				'goods_name'	=> $order['goods_name'],
				'goods_url'		=> $order['goods_url'],
				'goods_price'	=> $order['goods_price'],
				'goods_number'	=> $order['goods_number'],
				'final_price'	=> $order['final_price'],
				'remark'		=> '',
				'created'		=> full_date(),
			);
		
			//订单商品总金额
			$order['goods_amount'] = $order['goods_price'];
			
			//删除不需要的字段
			unset($order['goods_name']);
			unset($order['goods_url']);
			unset($order['goods_number']);
			unset($order['final_price']);

			//添加订单和商品
			$order_id = $this->add_order($order,$goods);
			
			if($order_id > 0){
				$add_count++;
			}
		}
		
		return $add_count;
	}
	
	/**
	 * 
	 * 添加订单
	 * @param $order
	 * @param $goods
	 */
	function add_order($order,$goods){

		//写入订单
		$cOrder 	= new Order();
		$order_id 	= $cOrder->add($order);
		
		if($order_id <= 0){
			return 0;
		}else{
			
			$goods['order_id']	= $order_id;

			//写入订单商品表
 			$cOrderGoods = new OrderGoods();	   
    		$add_count = $cOrderGoods->addAll(array($goods));

    		if($add_count > 0){
    			return $order_id;
    		}else{
    			return 0;
    		}
    		
		}
	}
	
	function lists($where = null){
			
		$whereSql = ' 1=1 ';
		
		//刷手条件
		$order_admin_sql = '';
		
		if(!is_null($where)){
						
			$where['end_time'] = short_date(strtotime($where['end_time']) + 86400);
			
			//查询条件
			$whereSql .= " AND (t.begin_time BETWEEN '{$where['begin_time']}' AND '{$where['end_time']}') ";

			if($where['plantform_id'] > 0){
				$whereSql .= " AND u.plantform_id = {$where['plantform_id']} ";
			}
			
			if($where['user_id'] > 0){
				$whereSql .= " AND u.user_id = {$where['user_id']} ";
			}
			
			//运维
			if(isset($where['business_admin_id'])){
				$whereSql .= " AND t.business_admin_id = {$where['business_admin_id']} ";
			}

			//支付状态
			if(isset($where['pay_status'])){
				$whereSql .= " AND t.pay_status = {$where['pay_status']} ";
			}
			
			
			//订单状态
			if(isset($where['task_status'])){
                if($where['task_status'] == -99){
                    $whereSql .= " AND t.task_status != -1 ";
                }else{
                    $whereSql .= " AND t.task_status = {$where['task_status']} ";
                }
            }
			
			//刷手
			if(isset($where['order_admin_id'])){
				$order_admin_sql = 'INNER JOIN (
    		
    					SELECT DISTINCT(task_id) AS task_id FROM orders WHERE order_admin_id = '.$where['order_admin_id'].'
    				) o ON o.task_id = t.task_id';
			}
			
		}
		
		$sql = <<<EOD
SELECT
	t.*,
	a.real_name AS business_admin_name,
	p.plantform_name,
	u.user_name,
	u.shop_name,
	u.shop_url,
	u.mobile_phone,
	REPLACE(stp.status_style,'#string',stp.status_name) AS pay_status_name,
	REPLACE(sts.status_style,'#string',sts.status_name) AS task_status_name,

	DATE_FORMAT(t.begin_time,'%Y-%m-%d') AS begin_time_fmt,
	DATE_FORMAT(t.end_time,'%Y-%m-%d') AS end_time_fmt,
	
	(t.task_order_money + t.commission_money + t.value_added_money) AS total_money,
	voe.exception_count,
	voe.finish_count
FROM task t

INNER JOIN admin a ON a.id = t.business_admin_id
INNER JOIN users u ON u.user_id = t.user_id
INNER JOIN plantform p ON p.plantform_id = u.plantform_id
INNER JOIN status_type stp ON stp.status_id = t.pay_status AND stp.type_code= 'task_pay_status'
INNER JOIN status_type sts ON sts.status_id = t.task_status AND sts.type_code= 'task_status'
INNER JOIN view_orders_exception voe ON voe.task_id = t.task_id

$order_admin_sql
WHERE $whereSql
ORDER BY t.begin_time DESC
		
EOD;

		$m = M('Task');
		return $m->query($sql);
	}
	
	/**
	 * 
	 * 汇总信息
	 * @param $where
	 */
	function summary($where = null){
		
		$whereSql = ' 1=1 ';
		if(!is_null($where)){
						
			$where['end_time'] = short_date(strtotime($where['end_time']) + 86400);
			
			//查询条件
			$whereSql .= " AND (t.begin_time BETWEEN '{$where['begin_time']}' AND '{$where['end_time']}') ";

			if($where['plantform_id'] > 0){
				$whereSql .= " AND u.plantform_id = {$where['plantform_id']} ";
			}
			if($where['user_id'] > 0){
				$whereSql .= " AND u.user_id = {$where['user_id']} ";
			}
			
			//支付状态
			if(isset($where['pay_status'])){
				$whereSql .= " AND t.pay_status = {$where['pay_status']} ";
			}

			//订单状态
			if(isset($where['task_status'])){

                //订单状态
                if(isset($where['task_status'])){
                    if($where['task_status'] == -99){
                        $whereSql .= " AND t.task_status != -1 ";
                    }else{
                        $whereSql .= " AND t.task_status = {$where['task_status']} ";
                    }
                }
			}
		}
		
		$m = M('Task');
		return $m->table('task t')
		->join('admin a ON a.id = t.business_admin_id')
		->join('users u ON u.user_id = t.user_id')
		->join('plantform p ON p.plantform_id = u.plantform_id')
		->join("status_type stp ON stp.status_id = t.pay_status AND stp.type_code= 'task_pay_status'")
		->join("status_type sts ON sts.status_id = t.task_status AND sts.type_code= 'task_status'")
		->field("
				SUM(t.order_count) AS order_count,
				SUM(t.task_order_money) AS task_order_money,
				SUM(t.commission_money) AS commission_money,
				SUM(t.value_added_money) AS value_added_money,
				(t.task_order_money + t.commission_money + t.value_added_money) AS total_money")
		->where($whereSql)
		->find();
	}
	
	/**
	 * 
	 * 修改任务单状态
	 * @param unknown_type $task_id
	 * @param unknown_type $task_status
	 * @param unknown_type $msg
	 */
	function update_task_status($task_id,$task_status,&$msg){
	
	 	//任务
	 	import('@.ORG.Task');
    	$cTask 	= new Task();
    	
    	import('@.ORG.Logs');
		$cLogs = new Logs();
			    	
		import('@.ORG.TaskLog');
		$cTaskLog = new TaskLog();
		
    	$task = $cTask->get_by_task_id($task_id);
    	
    	
    	//要变成协调中
    	if($task_status == TS_SETTLE){
    		
    		//检查支付状态
    	   	if($task['pay_status'] != TPS_CONFIRM_PAID){
	    		//不是 确认已付款
	    		$msg = '确认已付款的任务，才能开始协调';
	    		return false;
	    	}
	    	
    		
    		//任务未开始
	    	if($task['task_status'] == TS_UNSTART){
	    		//变成协调中
	    		$aft_row = $cTask->update($task_id, array(
	    			'task_status' => TS_SETTLE
	    		));
	    		
	    		if($aft_row > 0){
	    			
	    			//任务状态
		    			
	    			$task = $cTask->get_by_task_id($task_id);
    	
    				$log = array(
    					'task_id' 		=> $task_id,
    					'message' 		=> '开始协调',
    					'admin_id' 		=> admin_id_ajax(),
    					'task_status' 	=> $task['task_status'],
    					'pay_status' 	=> $task['pay_status']
    					
    				);
			    	
					//添加修改记录

			    	
			    	$log_result = $cTaskLog->add($log);
    				
			    	$msg = '任务单开始协调成功';
	    			 
	    			return true;
	    		}else{
	    			$msg = '任务状态修改为开始协调，操作失败';
	    			return false;
	    		}
	    	}
    	}
    	
    	//修改成执行中
    	else if($task_status == TS_RUNNING){
    	
    		//检查支付状态
    	   	if($task['task_status'] != TS_SETTLE){
	    		//不是 确认已付款
	    		$msg = '协调中的任务，才能开始执行';
	    		return false;
	    	}else{
	    		
	    		//变成执行中
	    		$aft_row = $cTask->update($task_id, array(
	    			'task_status' => TS_RUNNING
	    		));
	    		
	    		if($aft_row > 0){
	    			
	    			//任务状态
	    			$task = $cTask->get_by_task_id($task_id);
    	
    				$log = array(
    					'task_id' 		=> $task_id,
    					'message' 		=> '开始执行',
    					'admin_id' 		=> admin_id_ajax(),
    					'task_status' 	=> $task['task_status'],
    					'pay_status' 	=> $task['pay_status']
    					
    				);
			    	
					//添加修改记录
			    	$log_result = $cTaskLog->add($log);
    				
			    	$msg = '任务单开始执行成功';
	    			 
	    			return true;
	    		}else{
	    			$msg = '任务状态修改为执行中，操作失败';
	    			return false;
	    		}
	    	}
    	
    	}

    	
    	//修改成执行完毕 
    	else if($task_status == TS_FINISH){
    		
    		//检查支付状态
    	   	if($task['task_status'] != TS_RUNNING){
	    		//不是 确认已付款
	    		$msg = '执行中的任务，才能执行完毕';
	    		return false;
	    	}else{
	    		
	    		//变成执行中
	    		$aft_row = $cTask->update($task_id, array(
	    			'task_status' => TS_FINISH
	    		));
	    		
	    		if($aft_row > 0){
	    			
	    			//任务状态
	    			$task = $cTask->get_by_task_id($task_id);
    	
    				$log = array(
    					'task_id' 		=> $task_id,
    					'message' 		=> '执行完毕',
    					'admin_id' 		=> admin_id_ajax(),
    					'task_status' 	=> $task['task_status'],
    					'pay_status' 	=> $task['pay_status']
    					
    				);
			    	
					//添加修改记录
			    	$log_result = $cTaskLog->add($log);
    				
			    	$msg = '任务单执行完毕成功';
	    			 
	    			return true;
	    		}else{
	    			$msg = '任务状态修改为执行完毕，操作失败';
	    			return false;
	    		}
	    	}
    	}
	}
	
	
	/**
     * 
     * 已完成刷单的数量
     * @param $task_id
     */
    function task_order_finish_count($task_id){

    	$mOrders = M('Orders');
		return $mOrders->table('orders')
		->where("task_id = $task_id AND order_sn != ''")
		->getField('COUNT(*)');
    } 
}